package nxu.it.movieapi.service.mongo;

import nxu.it.api.common.param.PageQueryParam;
import nxu.it.api.common.result.BasePage;
import nxu.it.api.model.Comment;
import nxu.it.api.service.CommentService;
import nxu.it.movieapi.Doc.CommentDoc;
import nxu.it.movieapi.service.mapper.CommentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CommentServiceMongoImpl implements CommentService {

    @Autowired
    private MongoTemplate template;

    @Autowired
    private CommentMapper commentMapper;

    @Override
    public BasePage<Comment> pageByUserId(Integer userId, PageQueryParam pageQueryParam) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(PageRequest.of(pageQueryParam.getPageNumber() - 1, pageQueryParam.getPageSize()));

        List<CommentDoc> commentDocList = template.find(query, CommentDoc.class);
        List<Comment> commentList = commentMapper.fromDocList(commentDocList);

        long totalRow = template.count(Query.query(Criteria.where("userId").is(userId)), CommentDoc.class);
        int totalPage = (int) Math.ceil((double) totalRow / pageQueryParam.getPageSize());

        return new BasePage<>(commentList, pageQueryParam.getPageNumber(), pageQueryParam.getPageSize(), totalPage, (int) totalRow);
    }

    @Override
    public BasePage<Comment> pageByMovieId(Integer movieId, PageQueryParam pageQueryParam) {
        Query query = new Query(Criteria.where("movieId").is(movieId));
        long totalRow = template.count(query, CommentDoc.class);
        query.with(PageRequest.of(pageQueryParam.getPageNumber() - 1, pageQueryParam.getPageSize()));

        List<CommentDoc> commentDocList = template.find(query, CommentDoc.class);
        List<Comment> commentList = commentMapper.fromDocList(commentDocList);


        int totalPage = (int) Math.ceil((double) totalRow / pageQueryParam.getPageSize());

        return new BasePage<>(commentList, pageQueryParam.getPageNumber(), pageQueryParam.getPageSize(), totalPage, (int) totalRow);
    }

    private Sort getSort(PageQueryParam pageQueryParam) {
        String orderDirection = pageQueryParam.getOrderDirection();
        String orderField = pageQueryParam.getOrderField();
        Sort.Direction direction = "asc".equalsIgnoreCase(orderDirection) ? Sort.Direction.ASC : Sort.Direction.DESC;
        return Sort.by(direction, orderField);
    }
}
